'use client';

import { SectionHeader } from "@/components/section-header"
import { Badge } from "@/components/ui/badge"
import Link from "next/link"
import { useState, useMemo, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { listContents } from "@/apis/client/content";
import { Content } from "@/types/content";
import { Category } from "@/types/category";
import { useMenu } from "@/contexts/MenuContext";
import { SiteFooter } from "@/components/site-footer";

export default function NewsPage() {
    const [selectedCategory, setSelectedCategory] = useState<string | undefined>(undefined);
    const [page, setPage] = useState(1);
    const pageSize = 12;
    const { menus } = useMenu();

    const hotNewsMenu = useMemo(() => {
        return menus.find(menu => menu.sysCode === 'hot_news');
    }, [menus]);

    const categories = hotNewsMenu?.categories || [];

    // 使用 useQuery 缓存文章数据
    const { data: articlesData, isLoading, error } = useQuery({
        queryKey: ['news', hotNewsMenu?.id, selectedCategory, page],
        queryFn: () => {
            const categoryId = selectedCategory === "all" ? undefined : selectedCategory;
            return listContents({ 
                page, 
                pageSize, 
                categoryId, 
                type: 3, 
                menuId: hotNewsMenu!.id 
            });
        },
        enabled: !!hotNewsMenu?.id && selectedCategory !== undefined,
        staleTime: 5 * 60 * 1000, // 5分钟内数据被认为是新鲜的
        gcTime: 10 * 60 * 1000, // 10分钟后清除缓存
    });

    const articles = articlesData?.records || [];
    const total = articlesData?.total || 0;
    const totalPages = Math.ceil(total / pageSize);

    const stripHtml = (html: string) => html.replace(/<[^>]+>/g, "").trim();

    // 当菜单加载完成后，设置默认分类
    useEffect(() => {
        if (hotNewsMenu && selectedCategory === undefined) {
            setSelectedCategory('all');
        }
    }, [hotNewsMenu, selectedCategory]);

    // 保持页面结构不变，仅在内容区域展示加载或错误状态

    return (
        <main className="flex-1 overflow-y-auto flex flex-col">
            <div className="container mx-auto px-4 py-8 max-w-[1440px] flex-1">
                <SectionHeader title="热点资讯" icon="📰" showMore={false} />

                {/* Category Filter */}
                <div className="flex flex-wrap gap-2 mb-8">
                    <Badge
                        variant={selectedCategory === 'all' ? "default" : "outline"}
                        className="cursor-pointer hover:bg-primary hover:text-primary-foreground transition-colors"
                        onClick={() => {
                            setSelectedCategory('all');
                            setPage(1);
                        }}
                    >
                        全部
                    </Badge>
                    {categories.map((category) => (
                        <Badge
                            key={category.id}
                            variant={selectedCategory === category.id ? "default" : "outline"}
                            className="cursor-pointer hover:bg-primary hover:text-primary-foreground transition-colors"
                            onClick={() => {
                                setSelectedCategory(category.id);
                                setPage(1);
                            }}
                        >
                            {category.name}
                        </Badge>
                    ))}
                </div>

                {/* News Grid */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-8">
                    {isLoading && (
                        Array.from({ length: 3 }).map((_, idx) => (
                            <div key={idx} className="bg-card rounded-lg border border-border overflow-hidden h-64">
                                <div className="h-48 bg-muted animate-pulse" />
                                <div className="p-4 space-y-2">
                                    <div className="h-4 w-3/4 bg-muted animate-pulse rounded" />
                                    <div className="h-3 w-2/3 bg-muted animate-pulse rounded" />
                                    <div className="h-3 w-1/2 bg-muted animate-pulse rounded" />
                                </div>
                            </div>
                        ))
                    )}

                    {!isLoading && error && (
                        <div className="col-span-full flex items-center justify-center">
                            <div className="text-red-500">加载失败，请重试</div>
                        </div>
                    )}

                    {!isLoading && !error && articles.map((article) => (
                        <Link key={article.id} href={`/news/${article.id}`}>
                            <article className="bg-card rounded-lg border border-border overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group h-full">
                                <div className="relative h-48 overflow-hidden">
                                    <img
                                        src={article.cover?.url || "/icon/default.svg"}
                                        onError={(e) => { e.currentTarget.src = "/icon/default.svg"; e.currentTarget.onerror = null; }}
                                         alt={article.title}
                                         className="w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"
                                     />
                                    <Badge className="absolute top-3 left-3" variant="secondary">
                                        {article.categories?.[0]?.name}
                                    </Badge>
                                </div>
                                <div className="p-4">
                                    <h3 className="font-semibold text-lg mb-2 line-clamp-2 group-hover:text-primary transition-colors">
                                        {article.title}
                                    </h3>
                                    <p className="text-sm text-muted-foreground mb-3 line-clamp-2">{stripHtml(article.content || "")}</p>
                                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                                        <span>{new Date(article.createdAt).toLocaleDateString()}</span>
                                        <span className="flex items-center gap-1">
                                            <svg className="h-3 w-3" fill="currentColor" viewBox="0 0 20 20">
                                                <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                                                <path
                                                    fillRule="evenodd"
                                                    d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z"
                                                    clipRule="evenodd"
                                                />
                                            </svg>
                                            {article.viewCount}
                                        </span>
                                    </div>
                                </div>
                            </article>
                        </Link>
                    ))}
                </div>

                {/* Pagination */}
                {(
                    <div className="flex justify-center items-center gap-2">
                        <button
                            onClick={() => setPage(Math.max(1, page - 1))}
                            disabled={page === 1 || isLoading}
                            className="px-3 py-2 text-sm border border-border rounded-md hover:bg-accent disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            上一页
                        </button>
                        
                        <div className="flex items-center gap-1">
                            {totalPages > 0 ? (
                                Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                                    let pageNum;
                                    if (totalPages <= 5) {
                                        pageNum = i + 1;
                                    } else if (page <= 3) {
                                        pageNum = i + 1;
                                    } else if (page >= totalPages - 2) {
                                        pageNum = totalPages - 4 + i;
                                    } else {
                                        pageNum = page - 2 + i;
                                    }

                                    return (
                                        <button
                                            key={pageNum}
                                            onClick={() => setPage(pageNum)}
                                            disabled={isLoading}
                                            className={`px-3 py-2 text-sm border border-border rounded-md hover:bg-accent ${
                                                page === pageNum ? 'bg-primary text-primary-foreground' : ''
                                            } disabled:opacity-50 disabled:cursor-not-allowed`}
                                        >
                                            {pageNum}
                                        </button>
                                    );
                                })
                            ) : (
                                Array.from({ length: 5 }).map((_, i) => (
                                    <div key={i} className="h-9 w-9 rounded-md bg-muted animate-pulse border border-border" />
                                ))
                            )}
                        </div>
                        
                        <button
                            onClick={() => setPage(Math.min(totalPages, page + 1))}
                            disabled={isLoading || page === totalPages || totalPages === 0}
                            className="px-3 py-2 text-sm border border-border rounded-md hover:bg-accent disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            下一页
                        </button>
                        
                        <span className="text-sm text-muted-foreground ml-4">
                            第 {page} 页，共 {totalPages || '-'} 页
                        </span>
                    </div>
                )}
            </div>
            <SiteFooter />      
        </main>
    );
}
